package cn.bonoon.services.plugins;

import java.util.List;

import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.info.QuestionInfo;
import cn.bonoon.core.plugins.QuestionService;
import cn.bonoon.entities.interacting.QuestionEntity;
import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.support.services.AbstractService;

@Service
@Transactional(readOnly = true)
public class QuestionServiceImpl extends AbstractService<QuestionEntity> implements QuestionService {

	private static final String myql = "select new " + QuestionInfo.class.getName()
			+ "(x.question, x.answer, x.answered) from QuestionEntity x where x.creatorId=?";

	@Override
	public List<QuestionInfo> questioninfos(Long id, int skip, int size) {
		TypedQuery<QuestionInfo> query = __query(QuestionInfo.class, myql, id);
		return query.setFirstResult(skip).setMaxResults(size).getResultList();
	}

	@Override
	@Transactional
	public QuestionInfo save_ask(QuestionEntity entity) {
		entityManager.persist(entity);
		return new QuestionInfo(entity.getQuestion(), entity.getAnswer(), entity.isAnswered());
	}

	@Override
	public List<QuestionEntity> asks(IOperator opt, Long page) {
		String ql = "select x from QuestionEntity x where x.creatorId=?";
		TypedQuery<QuestionEntity> tqSelect = __query(QuestionEntity.class, ql, opt.getId());
		tqSelect.setFirstResult((int) ((page - 1) * 5));
		tqSelect.setMaxResults(5);
		return tqSelect.getResultList();
	}
	
	@Override
	protected QuestionEntity __update(OperateEvent event, QuestionEntity entity)throws Exception {
		entity.setAnswered(true);
		return super.__update(event, entity);
	}
	
}
